<?php
// +----------------------------------------------------------------------
// | 卡管理
// +----------------------------------------------------------------------
// | Author: huangzhen
// +----------------------------------------------------------------------

namespace app\cardeadmin\controller;

use app\api\controller\PublicApi;
use app\common\controller\AdminController;
use app\common\model\Cards as cardsModel;
use app\common\model\CardsLog;
use app\common\model\CardsTran;
use app\common\model\CardsTrans;
use app\common\model\CardsTransCredit;
use app\common\model\CardsTransCreditCd;
use app\common\model\CardsTransCreditLss;
use app\common\model\CardsTransFz;
use app\common\model\CardsTransFzTotal;
use app\common\model\CardsTransOther;
use app\common\model\ManageLog;
use app\common\model\UserSet;
use app\common\model\UserTranQz;
use app\index\model\UserLog;
use think\facade\Db;
use think\facade\View;
use think\facade\Cache;


/**
 * 卡管理
 * Class Operation
 * @package app\admin\controller
 */
class Cards extends AdminController
{
    /**
     * 操作列表
     */
    public function index()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new cardsModel();
            return $cdModel->tableDataAdmin($data);
        }
        $user_id = input('get.user_id' , '');
        $user_name = '';
        if(!empty($user_id)){
            $user_name = Db::name('user')->where(['id'=>$user_id])->value('username');
        }
        View::assign('user_name' , $user_name);
        return View::fetch();
    }

    public function updateCard()
    {
        $cdModel   = new cardsModel();
        $time      = getUtcTime();

        $create_card_course = Cache::store('redis')->get('updateCard' . $time);
        if($create_card_course){
            return $this->err('The card is being opened, please wait.');
        }else{
            $list = Db::name('cards')->where('check_status=0')
                ->limit(10)->select()->toArray();
            if(!empty($list)){
                $result    = $cdModel->updateCard($time);
                if($result){
                    return $this->scs('Confirm the successful.');
                }else{
                    return $this->err('Confirm the failed.');
                }
            }else{
                return $this->err('There are no cards to update.');
            }
        }
    }

    /**
     * 修复负值余额卡
     * @return \think\response\Json
     */
    public function updateCardInt()
    {
        $cdModel   = new cardsModel();
        $time      = getUtcTime();

        $create_card_course = Cache::store('redis')->get('updateCardInt' . $time);
        if($create_card_course){
            return $this->err('The card is being opened, please wait.');
        }else{
            $list = Db::name('cards')->where('balance < 0')
                ->select()->toArray();
            if(!empty($list)){
                $result    = $cdModel->updateCardInt($time);
                if($result >0){
                    return $this->scs("Confirm the successful.{$result}"  );
                }else{
                    return $this->err('Confirm the failed.');
                }
            }else{
                return $this->err('There are no cards to update.');
            }
        }
    }

    /**
     * 修复负值余额卡(卡Id数组)
     * @return \think\response\Json
     */
    public function updateCardIntOnly()
    {
        $cdModel   = new cardsModel();
        $time      = getUtcTime();

        $create_card_course = Cache::store('redis')->get('updateCardIntOnly' . $time);
        if($create_card_course){
            return $this->err('The card is being opened, please wait.');
        }else{
            $id_array  = input('post.id_array');
            $result    = $cdModel->updateCardIntOnly($time,$id_array);
            if($result >0){
                return $this->scs("Confirm the successful.{$result}"  );
            }else{
                return $this->err('Confirm the failed.');
            }
        }
    }

    public function changeCardStatus()
    {
        $data = input('param.');
        $num  = cardsModel::changeCardStatus($data , $this->manage_id);
        if($num){
            return $this->scs("{$num} 张卡更新成功.");
        }else{
            return $this->err('卡更新失败.');
        }
    }

    public function deleteCards()
    {
        $data = input('param.');
        $num  = cardsModel::deleteCards($data , $this->manage_id);
        if($num){
            return $this->scs("{$num} 张卡删除成功.");
        }else{
            return $this->err('卡删除失败.');
        }
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function cardLog()
    {
        if($this->request->isAjax()){
            $model = new CardsLog();
            return $model->tableDataAdmin(input('param.'));
        }
        $card_num = input('get.card_num' , '');
        $cycleAmountLimitUsed   = 0.00;
        $cycleAmountLimitHold   = 0.00;
        $api_amount             = 0.00;
        $api_amount_total       = 0.00;
        $availableBalance       = 0.00;
        $amountLimit            = 0.00;
        $bank_type              = '';
        $ctime                  = getUtcTime();
        if(!empty($card_num)){
            $card_list = Db::name('cards')->where(['card_num'=>$card_num])->find();
            if(!empty($card_list)){
                $card_id            = $card_list['id'];
                $user_id            = $card_list['user_id'];
                $card_status        = $card_list['status'];
                $card_type          = $card_list['card_type'];
                $balance_account    = $card_list['balance_account'];
                $bank_type          = $card_list['bank_type'];
                $card_balance       = $card_list['balance'];
                $card_token         = $card_list['card_token'];

                if($bank_type == 3){
                    $send_param         = [
                        "user_id"       => $user_id,
                        "card_num"      => $card_num,
                        "cardGuid"      => $card_token,
                        "action_type"   => "getCardDetail"
                    ];
//2025-9-3 因为有webhook了 这里不重复去比对消费日志
//                    cardsModel::saveTrans($user_id , $card_num ,$card_token,$card_status);

                    $check_card_api = PublicApi::requestApi('Connexpay',$send_param);
                    $return_blog    = $check_card_api['blog'];
                    $return_list    = $check_card_api['list'];
                    if($return_blog) {
                        $availableBalance = $return_list['availableBalance'];
                        $amountLimit = $return_list['amountLimit'];
                        $api_status = $return_list['status'];
                        if ($api_status == 'Card - Active') {
                            $api_status = 1;
                        } else if ($api_status == 'Card - Suspended') {
                            $api_status = 2;
                        } else if ($api_status == 'Card - Deactivated') {
                            $api_status = 3;
                        }
                        if ($api_status != $card_status) {
                            Db::name('cards')->where(['id' => $card_id])->update(['status' => $api_status]);
                            Db::name('user_log')->save([
                                'user_id' => $user_id,
                                'state' => 'lss_update_card_status',
                                'ctime' => $ctime,
                                'params' => json_encode([
                                    'card_num' => $card_num,
                                    'old_status' => $card_status,
                                    'new_status' => $api_status
                                ]),
                                'broswer' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                                'ip' => get_client_ip(0, true)
                            ]);
                        }
                        $blog_num = 0;
                        if ($api_status == 3) {
                            $blog_num = 1;
                        }
                        //银3 卡总金额与本地卡总金额不一致记录日志，已删除的卡是扣减等于1，其他是0
                        if (abs($amountLimit - $balance_account) != $blog_num) {
                            $error_type = 'lss_card_total_comparison';
                            Db::name('api_error')->save([
                                'user_id' => $user_id,
                                'amount' => $balance_account,
                                'amount_bank' => $amountLimit,
                                'type' => $error_type,
                                'data_param' => json_encode([
                                    'card_num' => $card_num,
                                    'balance' => $card_balance,
                                    'api_balance' => $availableBalance,
                                    'balance_account' => $balance_account,
                                    'api_balance_account' => $amountLimit
                                ]),
                                'ctime' => $ctime
                            ]);
                        }
                        if ($availableBalance - $card_balance != 0) {
                            $re = Db::name('cards')->where(['id' => $card_id])->update(['balance' => $availableBalance]);
                            Db::name('user_log')->save([
                                'user_id' => $user_id,
                                'state' => 'lss_update_card_balance',
                                'ctime' => $ctime,
                                'params' => json_encode([
                                    'card_num' => $card_num,
                                    'old_balance' => $card_balance,
                                    'new_balance' => $availableBalance
                                ]),
                                'broswer' => $_SERVER['HTTP_USER_AGENT'] ?? '',
                                'ip' => get_client_ip(0, true)
                            ]);
                        }
                    }
                }else{
                    //更新卡余额和卡状态
                    $up_card_balance_result = cardsModel::apiUpCardBalance($card_list);
                    $cycleAmountLimitUsed   = $up_card_balance_result['cycleAmountLimitUsed'];
                    $cycleAmountLimitHold   = $up_card_balance_result['cycleAmountLimitHold'];
                    $api_amount             = $up_card_balance_result['api_amount'];
                    $api_amount_total       = $up_card_balance_result['api_amount_total'];

                    //CardsTrans::apiUpCardTran($card_list);
                }
            }
        }
        View::assign([
            'api_amount_total'  => $api_amount_total,
            'api_amount'        => $api_amount,
            'amount_used'       => $cycleAmountLimitUsed,
            'amount_hold'       => $cycleAmountLimitHold,
            'card_num'          => empty($card_num)?'NULL' : $card_num,
            'bank_type'         => empty($bank_type)?'NULL' : $bank_type,
            'amountLimit'       => $amountLimit,
            'availableBalance'  => $availableBalance
        ]);
        return View::fetch();
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function cardPay()
    {
        if($this->request->isAjax()){
            $model = new CardsTran();
            return $model->tableDataAdmin(input('param.'));
        }
        View::assign([
            'tran_type'       => ['AUTHORIZATION' ,
                'PRE_AUTHORIZATION' ,
                'DECLINE' ,
                'POST' ,
                'REVERSAL',
                'CREDIT'
            ]
        ]);
        return View::fetch();
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function cardTran()
    {
        if($this->request->isAjax()){
            $model = new CardsTrans();
            return $model->tableDataAdmin(input('param.'));
        }
        View::assign([
            'tran_type'       => ['Authorized' ,
                'Posted' ,
                'Force Posted',
                'Declined',
                'Credit',
                'Reversal'
            ],

        ]);
        return View::fetch();
    }

    //非本系统卡消费
    public function cardTranNew()
    {
        if($this->request->isAjax()){
            $model = new CardsTrans();
            return $model->tableDataAdminNew(input('param.'));
        }
        return View::fetch();
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function cardTranOther()
    {
        if($this->request->isAjax()){
            $model = new CardsTransOther();
            return $model->tableDataAdmin(input('param.'));
        }
        View::assign([
            'tran_type'       => ['Authorized' ,
                'Posted' ,
                'Declined',
                'Credit',
                'Reversal'
            ],

        ]);
        return View::fetch();
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function tranCredit()
    {
        if($this->request->isAjax()){
            $model = new CardsTransCredit();
            return $model->tableDataAdmin(input('param.'));
        }
        $amount_sum = Db::name('cards_trans_credit')->sum('amount');
        $card_num   = input('get.card_num' , '');
        View::assign([
            'card_num'          => $card_num,
            'total_credit_amount'       => $amount_sum
        ]);
        return View::fetch();
    }

    public function addCreditLog()
    {
        $data = input('param.');
        $card_num = $data['card_num'] ?? '';
        if(!empty($card_num)){
            $re = self::bank1credit($card_num);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->err('Confirm the failed.');
            }
        }else{
            return $this->err('卡号不能为空.');
        }
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function tranCreditCd()
    {
        if($this->request->isAjax()){
            $model = new CardsTransCreditCd();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function tranForceTotal()
    {
        if($this->request->isAjax()){
            $model = new CardsTransFz();
            return $model->tableDataAdminTotal();
        }
        return View::fetch();
    }

    public function tranForceDec()
    {
        if($this->request->isAjax()){
            $model = new CardsTransFz();
            return $model->tableDataAdminDec();
        }
        return View::fetch();
    }

    public function tranForceButton()
    {
        if($this->request->isAjax()){
            $model = new CardsTransFz();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function tranForceKey()
    {
        if($this->request->isAjax()){
            $model = new UserTranQz();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function upTranKey()
    {
        $qz_list = Db::name('user_tran_qz')->order('ctime desc')->find();
        $ctime   = $qz_list['ctime'] ?? '';

        $where   = "ct.tran_status = 'Posted' 
                and ct.amount_auth >0 
                and ct.amount_post =0
                and ct.bank_type =3
                and c.status = 3";
        if(!empty($ctime)){
            $where .= " and ct.ctime > '{$ctime}'";
        }
        $list =Db::name('cards_trans')->alias('ct')
            ->leftJoin('cards c' , 'c.card_num=ct.card_num')
            ->field('ct.user_id,
            ct.card_num,
            ct.amount_auth,
            ct.amount_post,
            ct.utime ctime,
            c.status card_status')
            ->where($where)
            ->order('ct.utime asc')
            ->select()->toArray();
        $model = new UserTranQz();
        $re    = $model->saveAll($list);
        if($re){
            return $this->scs("Confirm the successful."  );
        }else{
            return $this->err('Confirm the failed.');
        }
    }
    public function editTranKey()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $remark      = trim($data['remark']);
            if(empty($remark)) return $this->err("Please input Remark.");
            $re         = Db::name('user_tran_qz')->where(['id'=>$data['qz_id']])
                ->update(['remark' => $remark]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $qz_id    = input('get.qz_id');
        $fz_desc  = Db::name('user_tran_qz')->where(['id' => $qz_id])->value('remark');
        View::assign([
            'qz_id'   => $qz_id,
            'desc'      => $fz_desc
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }
    public function editDesc()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $remark      = trim($data['remark']);
            if(empty($remark)) return $this->err("Please input Remark.");
            $re         = Db::name('cards_trans_fz')->where(['id'=>$data['fz_id']])
                ->update(['desc' => $remark]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $fz_id    = input('get.fz_id');
        $fz_desc  = Db::name('cards_trans_fz')->where(['id' => $fz_id])->value('desc');
        View::assign([
            'fz_id'   => $fz_id,
            'desc'      => $fz_desc
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    /**
     * Card Transactions
     * @return array|mixed|string
     * @throws \think\db\exception\DbException
     */
    public function tranCreditLss()
    {
        if($this->request->isAjax()){
            $model = new CardsTransCreditLss();
            return $model->tableDataAdmin(input('param.'));
        }
        return View::fetch();
    }

    public function CreditLssClose()
    {
        if($this->request->isAjax()){
            $model = new CardsTransCreditLss();
            return $model->tableDataAdminClose(input('param.'));
        }
        return View::fetch();
    }

    /**
     * 批量改变卡状态
     */
    public function changeCredit()
    {
        $model = new CardsTransCredit();
        $num   =  $model->changeCredit(input('param.') , $this->manage_id);
        if($num){
            return $this->scs("{$num} trans have been updated");
        }else{
            return $this->err('trans update failed');
        }
    }

    public function creditAmount()
    {
        $credit_id  = input('post.id');

        $model  = new CardsTransCredit();
        $result = $model::setCreditAmount($credit_id , $this->manage_id);
        if($result){
            return $this->scs('Credit successful.');
        }else{
            return $this->scs('Credit failed.');
        }
    }

    public function creditAmountClose()
    {
        $credit_id    = input('post.id');
        $user_amount  = input('post.user_amount' , 2);

        $list = Db::name('cards_trans_credit_lss')->where(['id' => $credit_id])->find();
        $card_num = $list['card_num'];
        $user_id  = $list['user_id'];
        $abs_amount = $list['amount'];
        $api_tran_shop = $list['shopping'];
        $credit_result = CardsTransCredit::endCredit([
            'card_num'      =>  $card_num,
            'user_id'       =>  $user_id,
            'credit_amount' =>  $abs_amount,
            'shopping'      =>  $api_tran_shop,
            'manage_id'     =>  $this->manage_id
        ] , $user_amount);
        if($credit_result){
            $credit_server_set = UserSet::getCardSet($user_id);
            $card_type         = substr($card_num , 0,6);
            $credit_server_set_rate = $credit_server_set[3][$card_type]['rate_refund'];
            $credit_server_amount = getSprintf(round($abs_amount * $credit_server_set_rate,2));
            $re = Db::name('cards_trans_credit_lss')->where(['id' => $credit_id])
                ->update([
                    'credit_status' => 1,
                    'utime' => getUtcTime(),
                    'server_amount' => $credit_server_amount
                ]);
            if($re){
                return $this->scs('Credit successful.');
            }else{
                return $this->scs('Credit failed.');
            }
        }else{
            return $this->scs('Credit failed.');
        }
    }

    public function creditRemark()
    {
        if($this->request->isPost()) {
            $data           = input('param.');
            $credit_id      = $data['credit_id'];
            $remark         = trim($data['remark']);
            $re = Db::name('cards_trans_credit')
                ->where(['id'=>$credit_id])
                ->update(['desc'=>$remark]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $id     = input('get.id');
        $list = Db::name('cards_trans_credit')->find($id);

        View::assign([
            'remark'        => $list['desc'],
            'credit_id'     => $id,
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public function tranShop()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new CardsTrans();
            return $cdModel->tableDataShop($data);
        }
        $list = Db::name('cards_trans_shop')->where(['id'=>1])->field('ctime')->find();

        $time = isset($list['ctime']) ? date('Y-m-d H:i:s',$list['ctime'] + 8*60*60) : '--';

        View::assign([
            'time'     => $time
        ]);
        return View::fetch();
    }

    public function tranShopUp()
    {
        $cdModel = new CardsTrans();
        $ctime   = getUtcTime();
        $result = $cdModel->getShops($ctime);
        if($result){
            return $this->scs('Confirm the successful.' , '' ,
                [
                    'time'              => date('Y-m-d H:i:s',$ctime + 8*60*60),
                ]);
        }else{
            return $this->scs('Confirm the failed.');
        }
    }

    public function tranShopUser()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new CardsTrans();
            return $cdModel->getShopsUser($data);
        }
        return View::fetch();
    }

    public function getCardNum()
    {
        $card_id = input('get.card_id');

        $model = new cardsModel();
        $list = $model->setCardDetail($card_id);
        $token= '';
        if(isset($list['token'])){
            $token = $list['token'];
        }
        View::assign([
            'token'         => $token,
        ]);
        View::layout(false);
        return View::fetch();
    }

    public function upBalance()
    {
        $card_id = input('post.card_id');
        $re      = cardsModel::checkCardBalanceApi($card_id , "searchExpDate2" , true);
        if($re){
            return $this->scs('up success');
        }else{
            return $this->err('up error');
        }
    }

    public function cardDelList()
    {
        if($this->request->isPost()) {
            $data = input('param.');
            $cdModel = new cardsModel();
            return $cdModel->tableDataDel($data);
        }
        $card_num = trim(input('get.card_num'));
        $cycleAmountLimitUsed   = 0.00;
        $cycleAmountLimitHold   = 0.00;
        $api_amount             = 0.00;
        $api_amount_total       = 0.00;
        $cardStatus             = '---';
        $card_list              = Db::name('cards')->where(['card_num'=>$card_num])->find();
        $bank_type              = $card_list['bank_type'];
        if(!empty($card_num) && substr($card_num ,0 ,6) == 556766){
            $send_param         = [
                "user_id"       => 0,
                "action_type"   => "searchExpDate2",
                "card_type"     => 556766,
                "bank_type"     => $bank_type,
                "post_param"    => [
                    "card_num"  => $card_num,
                ]
            ];
            $check_card_api = PublicApi::requestApi('Comdata',$send_param);
            $return_blog    = $check_card_api['blog'];
            $return_list    = $check_card_api['list'];
            if($return_blog) {
                $api_amount       = $return_list['cycleAmountLimitAvailable'];
                $api_amount_total = $return_list['cycleAmountLimit'];
                $cycleAmountLimitUsed = $return_list['cycleAmountLimitUsed'];
                $cycleAmountLimitHold = $return_list['cycleAmountLimitHold'];
                $cardStatus       = $return_list['cardStatus'];
            }
        }
        View::assign([
            'api_amount_total'  => $api_amount_total,
            'api_amount'        => $api_amount,
            'amount_used'       => $cycleAmountLimitUsed,
            'amount_hold'       => $cycleAmountLimitHold,
            'card_num'          => $card_num,
            'card_status'       => $cardStatus
        ]);
        return View::fetch();
    }

    /**
     * 删除vva平台外的556766卡
     * @return \think\response\Json
     */
    public function delCard()
    {
        $data           = input('param.');
        $card_num       = trim($data['card_num']);
        $card_balance   = $data['card_balance'];
        $card_used      = $data['card_used'];
        $update_card_param      = [
            "user_id"       => 0,
            "action_type"   => 'card_del',
            "card_type"     => 556766,
            "post_param"  => [
                "card_num"  => $card_num
            ]
        ];
        $create_card_api= PublicApi::requestApi('Comdata',$update_card_param);
        $return_blog    = $create_card_api['blog'];
        if($return_blog) {
            //记录管理员操作日志
            ManageLog::saveManageLog([
                'manage_id' => $this->manage_id,
                'desc' => 'manage_card_del',
                'time' => getUtcTime(),
                'content' => json_encode([
                    'card_num' => $card_num,
                    'username' => 'other platform'
                ])
            ]);
            Db::name('cards_del')->save([
                'card_num'      => $card_num,
                'card_balance'  => $card_balance,
                'card_used'     => $card_used,
                'plat'          => 1, //1代表外平台
                'ctime'         => getUtcTime()
            ]);
        }
        $num = 0;
        if($num){
            return $this->scs("{$num} 张卡删除成功.");
        }else{
            return $this->err('卡删除失败.');
        }
    }

    /**
     * 编辑余额
     * @author 救火队队长
     */
    public function debitBalance()
    {
        if($this->request->isPost()) {
            $data       = input('param.');
            $amount      = $data['amount'];
            $card_id    = $data['card_id'];
            $manage_id  = $this->manage_id;
            if(!check_param($amount , 'zfInt')) return $this->err("It must be a positive integer.");
            if($amount == 0) return $this->err("Amount cannot be equal to 0.");
            $cardModel = new cardsModel();
            $card_info = $cardModel->where(['id' => $card_id])->find();
            $status    = $card_info['status'];
            $curr_balance = $card_info['balance'];
            $user_id   = $card_info['user_id'];
            if ($status != 1) return $this->err('已激活状态才能进行此操作.');
            if ($amount - $curr_balance> 0) return $this->err('卡余额不足.');
            $re = $cardModel->adminCardBalance('deduct_card_balance', $data + [
                    'user_id'   => $user_id,
                    'manage_id' => $manage_id
                ]);
            if($re){
                return $this->scs('Confirm the successful.');
            }else{
                return $this->scs('Confirm the failed.');
            }
        }

        $card_id = input('get.card_id');
        $cardModel = new cardsModel();
        $card_info = $cardModel->where(['id' => $card_id])->find();
        View::assign([
            'card_id'       => $card_id,
            'balance'       => $card_info['balance'],
            'card_num'      => $card_info['card_num'],
        ]);
        View::layout(false);
        return [
            'status'    => 1,
            'datas'     => View::fetch()
        ];
    }

    public static function bank1credit($card_num)
    {
        if(substr($card_num , 0 , 6) != 556766){
            $list = Db::name('api_accept_com')
                ->where(['card_num'=>$card_num , 'tran_type' => 'CREDIT'])
                ->select()->toArray();

            if($list){
                $card_status = Db::name('cards')->where(['card_num'=>$card_num])->value('status');
                $i = 0;
                $aa = [];
                foreach ($list as $k=>$v){
                    $idMatchNumber  = $v['idMatchNumber'];
                    $user_id        = $v['user_id'];
                    $approvalCode   = $v['app_code'];
                    $auth_amount    = $v['auth_amount'];
                    $post_amount    = $v['post_amount'];
                    $reversalFlag   = $v['flag'];
                    $authorizationTime = $v['auth_time'];
                    $card_num       = $v['card_num'];
                    $bank_type      = 1;
                    $ctime          = $v['auth_time'];

                    $json_data      = json_decode($v['json_data'] , true);
                    $tran_pos_array = $json_data['pos'] ?? '';
                    $shopping       = $tran_pos_array['acceptLocation'] ?? '';
                    $transactionTime= $json_data['transactionTime'] ?? '';
                    if(!empty($transactionTime)){
                        $transactionTime = substr($transactionTime , 0 , 19);
                    }

                    $country        = !empty($shopping) ? substr($shopping , -2) : '';
                    $currencyCode   = 'USD';

                    $credit_check = Db::name('cards_trans')->where([
                        'card_num'           => $card_num,
                        'idMatchNumber'      => $idMatchNumber,
                        'tran_status'        => 'Credit'
                    ])->find();

                    if(empty($credit_check)){
                        $insert_data =[
                            'user_id'       => $user_id,
                            'app_code'      => $approvalCode,
                            'card_num'      => $card_num,
                            'amount_auth'   => $auth_amount,
                            'amount_post'   => $post_amount,
                            'reversal_flag' => $reversalFlag,
                            'shopping'      => $shopping,
                            'ctime'         => $authorizationTime,
                            'bank_type'     => $bank_type,
                            'desc'          => '',//当状态为DECLINE,这里会有数据，否者为0
                            'idMatchNumber' => $idMatchNumber,
                            'country'       => $country,
                            'currencyCode'  => $currencyCode,
                            'tran_status'   => 'Credit',
                        ];
                        $aa[] = $insert_data;
                        Db::name('cards_trans')->save($insert_data);
                    }

                    $credit_check_log = Db::name('cards_trans_credit')->where([
                        'card_num'           => $card_num,
                        'idMatchNumber'      => $idMatchNumber,
                    ])->find();
                    if(empty($credit_check_log)){
                        $abs_amount = abs($post_amount);
                        $credit_add = [
                            'card_num'      => $card_num,
                            'amount'        => $abs_amount,
                            'ctime'         => $transactionTime,
                            'idMatchNumber' => $idMatchNumber,
                            'user_id'       => $user_id,
                            'shopping'      => $shopping,
                            'card_status'   => $card_status
                        ];
                        Db::name('cards_trans_credit')->save($credit_add);
                    }
                }
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}
